package middleware

import (
	"192.168.1.75/go-pkg/logx"
	"github.com/gin-gonic/gin"
	"runtime/debug"
)

// CustomRecovery 自定义panic恢复中间件
func RecoveryMiddleware() gin.HandlerFunc {
	return gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
		spanCtx := logx.Start(c.Request.Context(), "panic recovery")
		defer logx.End(spanCtx)

		stack := string(debug.Stack())
		logx.Error(spanCtx, "panic recovered",
			logx.String("url", c.Request.URL.RequestURI()),
			logx.String("method", c.Request.Method),
			logx.Any("panic", recovered),
			logx.String("stack", string(debug.Stack())),
		)

		c.AbortWithStatusJSON(500, gin.H{
			"code": "-1",
			"msg":  "Internal Server Error",
			"data": map[string]string{
				"stack": stack,
			},
		})
	})
}
